package com.laikan.reader.bookfriend.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.permission.CheckPermission;
import com.laikan.library.permission.PermissionActivity;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookfriend.bean.PersonalInfoBean;
import com.laikan.reader.bookreader.activity.SendCommentActivity;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.databinding.PersonalInfoActivityBinding;
import com.socks.library.KLog;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;

/**
 * Created by wx
 *
 * @date 2016/4/27/10:02
 * @description 个人资料页面
 */
public class PersonalInfoActivity extends BasicActivity {

    private ImageView back_tv, photo_right_enter, nickname_right_enter, gender_right_enter, birthday_right_enter, iv_person_sign;
    private Drawable drawable_back_tv, drawable_right_jiantou;
    private RelativeLayout back_layout;
    private File temp;
    PersonalInfoActivityBinding piab;
    PersonalInfoBean pib;

    private static final int REQUEST_CODE = 0;//请求码

    private CheckPermission checkPermission;//检测权限器

    //配置需要取的权限
    static final String[] PERMISSION = new String[]{
        Manifest.permission.CAMERA,// 相机使用权限
    };

    @Override
    protected void assignViews() {
        piab = DataBindingUtil.setContentView(this, R.layout.personal_info_activity);
        checkPermission = new CheckPermission(this);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        photo_right_enter = (ImageView)findViewById(R.id.photo_right_enter);
        nickname_right_enter = (ImageView)findViewById(R.id.nickname_right_enter);
        gender_right_enter = (ImageView)findViewById(R.id.gender_right_enter);
        birthday_right_enter = (ImageView)findViewById(R.id.birthday_right_enter);
        iv_person_sign = (ImageView)findViewById(R.id.iv_person_sign);
    }

    @Override
    protected void initData() {
        pib = (PersonalInfoBean)getIntent().getSerializableExtra("personalInfoBean");
        piab.setPib(pib);
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);

        drawable_right_jiantou = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_enter_small), Color.parseColor("#cccccc")));
        photo_right_enter.setImageDrawable(drawable_right_jiantou);
        nickname_right_enter.setImageDrawable(drawable_right_jiantou);
        gender_right_enter.setImageDrawable(drawable_right_jiantou);
        birthday_right_enter.setImageDrawable(drawable_right_jiantou);
        iv_person_sign.setImageDrawable(drawable_right_jiantou);
    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
    }

    //clickbind    -->   跳转到我的性别页面
    public void changeGender(View view) {
        Intent intent5 = new Intent(mContext, GenderActivity.class);
        intent5.putExtra("gender", pib.getUserGender());
        startActivityForResult(intent5, 5);
    }

    //clickbind    -->   跳转到出生日期页面
    public void changeBirthday(View view) {
        Intent intent6 = new Intent(mContext, BirthdayActivity.class);
        intent6.putExtra("birthday", pib.getUserBirthday());
        startActivityForResult(intent6, 6);
    }

    //clickbind    -->   跳转到修改昵称页面
    public void changeNickName(View view) {
        startActivityForResult(new Intent(mContext, NickName.class), 1);
    }

    //clickbind    -->   跳转更新用户头像页面
    public void changeUserAvator(View view) {
        if (Build.VERSION.SDK_INT > 22 && checkPermission.permissionSet(PERMISSION)) {
            startPermissionActivity();
        }else {
            showPickDialog();
        }
    }

    //clickbind    -->   跳转更新用户签名
    public void changeUserSign(View view) {
        Intent signIntent = new Intent(mContext, SendCommentActivity.class);
        signIntent.setAction("from_person_sign");
        signIntent.putExtra("exis_content", pib.getUserIntroduce());
        startActivityForResult(signIntent, 7);
    }

    @Override
    protected void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.back_layout:
                //关闭当前页面
                this.finish();
                break;
            default:
                break;
        }
    }

    /**
     * 显示设置头像的对话框
     */
    private void showPickDialog() {
        new AlertDialog.Builder(mContext).setTitle(R.string.personal_info_setup).setNegativeButton(R.string.personal_info_photo_gallery, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 2);
            }
        }).setPositiveButton(R.string.personal_info_photograph, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/LaikanReader", "person.jpg")));
                startActivityForResult(intent, 3);
            }
        }).show();
    }

    /**
     * 处理返回后的数据结果
     *
     * @param requestCode 请求码
     * @param resultCode 返回的状态
     * @param data 返回的数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //拒绝时，没有获取到主要权限，无法运行，关闭页面
        if (requestCode == REQUEST_CODE && resultCode == PermissionActivity.PERMISSION_DENIEG) {
            finish();
        }

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    if (data != null) {
                        String nickName = data.getStringExtra("nick");
                        pib.setUserName(nickName);
                    }
                    break;
                case 2:
                    if (data != null) {
                        String mAlbumPicturePath = getPicturePath(getApplicationContext(), data.getData());
                        startPhotoZoom(Uri.fromFile(new File(mAlbumPicturePath)));
                    }
                    break;
                //调用摄像头拍照
                case 3:
                    temp = new File(Environment.getExternalStorageDirectory() + "/LaikanReader/person.jpg");
                    startPhotoZoom(Uri.fromFile(temp));
                    break;
                case 4:
                    if (data != null) {
                        //保存裁剪后的图片
                        temp = new File(Environment.getExternalStorageDirectory() + "/LaikanReader/person.jpg");
                        setPicToView(Uri.fromFile(temp), data);
                    }
                    break;
                case 5:
                    if (data != null) {
                        String gender = data.getStringExtra("return_gender");
                        pib.setUserGender(gender);
                    }
                    break;
                case 6:
                    if (data != null) {
                        String date = data.getStringExtra("return_birth");
                        pib.setUserBirthday(date);
                    }
                    break;
                case 7:      // 个性签名
                    if (data != null) {
                        String sign = data.getStringExtra("sign");
                        pib.setUserIntroduce(sign);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 裁剪图片实现
     *
     * @param uri 需要裁剪的图片的唯一地址
     */
    private void startPhotoZoom(Uri uri) {
        //对拍出的照片进行裁剪
        KLog.i("PersonalInfoActivity startPhotoZoon uri: " + uri);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("scale", true);
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);   //设置裁剪时不对裁剪的图片进行面部特征侦测
        startActivityForResult(intent, 4);
    }

    /**
     * <br>功能简述:4.4及以上获取图片的方法
     * <br>功能详细描述:
     * <br>注意:
     *
     * @param context
     * @param uri
     *
     * @return
     */
    @TargetApi (Build.VERSION_CODES.KITKAT)
    public static String getPicturePath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                }else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                }else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri)) { return uri.getLastPathSegment(); }

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        }finally {
            if (cursor != null) { cursor.close(); }
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     *
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     *
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     *
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     *
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    /**
     * 保存裁剪后的图片数据
     */

    private void setPicToView(Uri uri, Intent picdata) {
        //选择提示对话框
        upImage(uri, picdata);

    }

    private void upImage(final Uri uri, final Intent dataIntent) {
        new AlertDialog.Builder(mContext).setTitle(R.string.personal_info_whether_upload).setNegativeButton(R.string.personal_info_yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭对话框
                Bundle extraData = dataIntent.getExtras();
                if (extraData != null) {
                    final Bitmap photo = extraData.getParcelable("data");
                    bitmapToFile(photo, 300, 300);//图片压缩后存到本地文件
                }
            }
        }).setPositiveButton(R.string.personal_info_no, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭对话框
            }
        }).show();
    }

    /**
     * 将图片压缩后存到本地文件
     *
     * @param bmp
     * @param width
     * @param height
     */
    private void bitmapToFile(Bitmap bmp, int width, int height) {
        FileOutputStream fileOutputStream = null;
        try {
            //图片存储的路径
            fileOutputStream = new FileOutputStream(Environment.getExternalStorageDirectory() + "/LaikanReader/person.jpg");
            // 压缩bitmap写进outputStream 参数：输出格式 输出质量 目标OutputStream
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            //关闭输出流
            fileOutputStream.close();
            //上传图片
            uploadimg(new File(Environment.getExternalStorageDirectory() + "/LaikanReader/person.jpg"), width, height);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void uploadimg(File file, int width, int height) {
        HashMap map = new HashMap();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("left", "0");
        map.put("top", "0");
        map.put("width", width + "");
        map.put("height", height + "");

        if (!file.exists()) {
            Toast.makeText(getApplicationContext(), R.string.personal_info_test, Toast.LENGTH_SHORT).show();
            return;
        }

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                ImagePipeline imagePipeline = Fresco.getImagePipeline();
                imagePipeline.clearCaches();
                pib.setUserAvatorUrl(Uri.fromFile(temp).toString());
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL2() + "iconupload");
        requester.setMapBody(map);
        requester.setPartFileName("uploadfile");
        requester.setPartFile(file);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    //进入权限设置页面
    private void startPermissionActivity() {
        PermissionActivity.startActivityForResult(this, REQUEST_CODE, PERMISSION);
    }
}
